package org.mosquitos;

import java.util.Enumeration;

import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.exception.PeerGroupException;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.protocol.DiscoveryResponseMsg;
import net.jxta.protocol.PeerAdvertisement;

public class DiscoveryDemo implements Runnable, DiscoveryListener {
	static PeerGroup netPeerGroup = null;
	private DiscoveryService discovery;

	// 开始配置JXTA平台
	private void startJxta() {
		try {
			netPeerGroup = PeerGroupFactory.newNetPeerGroup();
		} catch (PeerGroupException e) {

			// 如果不能实例化Peer Group，输出原因并结束程序。
			System.out.println("Fatal error : group creation failure");
			e.printStackTrace();
			System.exit(1);
		}

		// 从Peer Group中发现的服务器
		discovery = netPeerGroup.getDiscoveryService();
	}

	public void run() {
		discovery.addDiscoveryListener(this);

		while (true) {
			System.out.println("Sending a Discovery Message");

			// 寻找Peers，每个Peer最多反馈5个
			//discovery.getRemoteAdvertisements(null, DiscoveryService.PEER,null,null,5,this);
			discovery.getRemoteAdvertisements(null, DiscoveryService.PEER,null, null, 5);

			try {
				Thread.sleep(60 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	public void discoveryEvent(DiscoveryEvent ev) {
		DiscoveryResponseMsg res = ev.getResponse();
		String name = "unknown";

		// 获得Peers的反馈广告
		PeerAdvertisement peerAdv = res.getPeerAdvertisement();

		// 一些Peers不能反馈他们的 PeerAdvertisement
		if (peerAdv != null) {
			name = peerAdv.getName();
		}

		System.out.println("Got a Discovery Response ["+ res.getResponseCount() + " elements] from peer : " + name);

		// 输出发现的Peer
		PeerAdvertisement adv = null;
		Enumeration enum_ = res.getAdvertisements();

		if (enum_ != null) {
			while (enum_.hasMoreElements()) {
				adv = (PeerAdvertisement) enum_.nextElement();
				System.out.println(" Peer  = " + adv);
				System.out.println(" Peer name = " + adv.getName());
			}
		}

	}

	static public void main(String args[]) {
		DiscoveryDemo myapp = new DiscoveryDemo();
		myapp.startJxta();
		myapp.run();
	}
}
